package com.fbt.transfer.app.driver.util;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

public class PermissionManager {
    private static final String TAG = "PermissionManager";
    private static final String PREF_NAME = "permission_pref";
    private static final String KEY_LAST_PERMISSION_REMINDER = "last_permission_reminder";
    private static final long REMINDER_INTERVAL = 24 * 60 * 60 * 1000; // 24小时
    private static PermissionManager instance;
    private final SharedPreferences preferences;

    private PermissionManager(Context context) {
        preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    }

    public static PermissionManager getInstance(Context context) {
        if (instance == null) {
            synchronized (PermissionManager.class) {
                if (instance == null) {
                    instance = new PermissionManager(context.getApplicationContext());
                }
            }
        }
        return instance;
    }

    public boolean hasOverlayPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return Settings.canDrawOverlays(context);
        }
        return true;
    }

    public void requestOverlayPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + context.getPackageName()));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

    public boolean shouldShowPermissionReminder() {
        long lastReminder = preferences.getLong(KEY_LAST_PERMISSION_REMINDER, 0);
        return System.currentTimeMillis() - lastReminder >= REMINDER_INTERVAL;
    }

    public void updateLastReminderTime() {
        preferences.edit().putLong(KEY_LAST_PERMISSION_REMINDER, System.currentTimeMillis()).apply();
    }
} 